package com.lpc.android.abc.base.base;

import com.lpc.android.abc.base.api.ApiCallback;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by lpc on 2016/12/17.
 */

public class BasePresenter<M extends IModel, V extends IView> {

    /**
     * 持有所有的Subscriptions
     */
    protected CompositeSubscription mCompositeSubscription;

//    protected LoginContract.View view;

    protected M mModel;

    protected V mView;

    public BasePresenter(V view) {

        mCompositeSubscription = new CompositeSubscription();
        this.mView = view;
    }

    /**
     * 页面关闭后要把回调滞空，否则容易空指针
     *
     * @param apiCallback
     * @param <T>
     * @return
     */
    protected <T> Subscriber<T> newMySubscriber(final ApiCallback<T> apiCallback) {

        return new Subscriber<T>() {

            @Override
            public void onStart() {
                super.onStart();
                if (mView != null) {
                    mView.showLoadingDialog();
                }
                apiCallback.onStart();

            }

            @Override
            public void onCompleted() {

                apiCallback.onCompleted();
                if (mView != null) {
                    mView.hideLoadingDialog();
                }
            }

            @Override
            public void onError(Throwable e) {

                apiCallback.onError(e);
                if (mView != null) {
                    mView.hideLoadingDialog();
                }
            }

            @Override
            public void onNext(T t) {

                apiCallback.onNext(t);
            }

        };

    }

    public void onDestory() {

        onUnsubscribe();

        if(mModel != null){
            mModel.onDestory();
            mModel = null;
        }

        if(mView != null){
            mView = null;
        }

    }

    /*protected void addSubscription(Subscription subscription) {

        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }

        mCompositeSubscription.add(subscription);
    }*/

    protected <T> void addSubscription(Observable<T> observable, Subscriber<T> subscriber) {

        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }

        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    protected void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }
}
